package com.naihe.anderson.sms.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.text.ClipboardManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.TalkMessageAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.entity.Nhsms;
import com.naihe.anderson.sms.entity.NhsmsSession;
import com.naihe.anderson.sms.listener.OnNotifyDataNhSmsListener;
import com.naihe.anderson.sms.manager.ContactMgr;
import com.naihe.anderson.sms.manager.NhSmsMgr;
import com.naihe.anderson.sms.util.LinkifyUtil;
import com.naihe.anderson.sms.widgets.AppPanel;
import com.naihe.anderson.sms.widgets.LongClickDialog;
import com.naihe.anderson.sms.widgets.PullToRefreshListView;
import com.naihe.anderson.sms.widgets.PullToRefreshListView.OnRefreshListener;

public class TalkMessageActivity extends Activity implements
OnItemClickListener, OnItemLongClickListener, OnClickListener, OnRefreshListener, OnNotifyDataNhSmsListener{

	public static final int MSG_WHAT_DATA_CHANGE = 0;
	public static final int MSG_WHAT_SET_SELECTION = 1;
	public static final int MSG_WHAT_UPDATE_READ = 2;
	public static final int MSG_WHAT_MENU_COLLECTION_SESSION = 3;
	
	private static final int ITEM_LONG_CLICK_COPY_INDEX = 0;
	TextView smsName;
	TextView smsCallnum;
	ImageView contactImage;
	Button talkmessageCall;
	ImageButton talkmessageSend;
	EditText talkmessageForbody;
	PullToRefreshListView talkmessage_list;
	
	AppPanel appPanel;
	Button makenewPlusFile;
	
	TalkMessageAdapter messageAdapter;
	
	NhsmsSession nhsmsSession;
	ContactMgr contactMgr;
	NhSmsMgr nhSmsMgr;
	ContactUser contactUser;
	
	NhSmsApp nhSmsApp;
	int pageNumber = 1;
	
	List<Nhsms> nhsmsList = new ArrayList<Nhsms>();
	
	Handler mHandler = new Handler(){

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_DATA_CHANGE:
				dataChange((List<Nhsms>) msg.obj);
				break;
			case MSG_WHAT_SET_SELECTION:
				talkmessage_list.setSelection(msg.arg1);
				break;
			case MSG_WHAT_UPDATE_READ:
				nhSmsMgr.updateNhSessionRead(nhsmsSession.getTid());
				break;
			case MSG_WHAT_MENU_COLLECTION_SESSION://加密
				if(mPopupWindow == null)
					initPopupWindows();
				
				mPopupWindow.update();
				mPopupWindow.showAtLocation(findViewById(R.id.sms_name), Gravity.CENTER, 0, 0);
				break;
			default:
				break;
			}
		}
		
	};
	
	private void dataChange(List<Nhsms> dataChangeList){
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_SET_SELECTION;
		message.arg1 = nhsmsList.size();
		
		nhsmsList.clear();
		nhsmsList.addAll(dataChangeList);
		
		dataChangeList.clear();
		dataChangeList = null;
		
		if(nhsmsList.size() < nhsmsSession.getNumsize()){
			talkmessage_list.setHasHistoryData(true);
    	} else {
    		talkmessage_list.setHasHistoryData(false);
    	}
		talkmessage_list.resetHeaderPadding();
		messageAdapter.notifyDataSetChanged();
		
		mHandler.sendMessageDelayed(message, 50);
		nhSmsMgr.updateNhSessionRead(nhsmsSession.getTid());
	}
	
	PopupWindow mPopupWindow = null;
	EditText editText;
	private void initPopupWindows(){
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.popup_edit_layout, null);
        editText = (EditText) popunwindwow.findViewById(R.id.baseSignature_edit);
        Button checkbtn_cancel =(Button) popunwindwow.findViewById(R.id.checkbtn_cancel);
        Button checkbtn_ok =(Button) popunwindwow.findViewById(R.id.checkbtn_ok);
        TextView title_text = (TextView) popunwindwow.findViewById(R.id.title_text);
       
        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editText.setHint(getResources().getString(R.string.save_key_word));
        
        title_text.setText(getResources().getString(R.string.menu_btn_text_menu_top_3));
        checkbtn_cancel.setOnClickListener(TalkMessageActivity.this);
        checkbtn_ok.setOnClickListener(TalkMessageActivity.this);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setOutsideTouchable(false);  
        mPopupWindow.setFocusable(true);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talkmns_message_layout);
        nhSmsApp = ((NhSmsApp)getApplication());
        contactMgr = nhSmsApp.getContactMgr();
        nhsmsSession = (NhsmsSession) getIntent().getExtras().get("NhsmsSession");
        contactUser = contactMgr.getContactUserById(contactMgr.getContactIdByPhoneNum(nhsmsSession.getAddress()));
        nhSmsMgr = nhSmsApp.getNhSmsMgr();
        
        initView();
        if(!TextUtils.isEmpty(nhsmsSession.getCipher())){
        	mHandler.sendEmptyMessageDelayed(MSG_WHAT_MENU_COLLECTION_SESSION, 10);
        } else {
        	initListView();
        	mHandler.sendEmptyMessage(MSG_WHAT_UPDATE_READ);
        }
    }
	
	@Override
	protected void onResume() {
		nhSmsApp.getNotificationMgr().setOldSessionID(nhsmsSession.getTid());
		nhSmsMgr.setDataSetChangForSmsListener(TalkMessageActivity.this, nhsmsSession.getTid());
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onStop() {
		nhSmsApp.getNotificationMgr().setOldSessionID(-1);
		nhSmsApp.getNotificationMgr().cancelNotif();
		super.onStop();
	}
	
	private void initView(){
		appPanel = (AppPanel) findViewById(R.id.makenew_appPanel);
		makenewPlusFile = (Button) findViewById(R.id.talkmessage_plus_file);
		makenewPlusFile.setOnClickListener(this);
		
		talkmessageForbody = (EditText) findViewById(R.id.talkmessage_forbody);
		talkmessageForbody.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
            	if(appPanel.isShown())
    				appPanel.setVisibility(View.GONE);
                return false;
            }
        });
		
		smsName = (TextView) findViewById(R.id.sms_name);
		smsCallnum = (TextView) findViewById(R.id.sms_callnum);
		talkmessage_list = (PullToRefreshListView) findViewById(R.id.talkmessage_list);
		talkmessage_list.setOnItemLongClickListener(this);
		talkmessage_list.setOnRefreshListener(this);
		talkmessage_list.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				if(appPanel.isShown())
    				appPanel.setVisibility(View.GONE);
				return false;
			}
		});
        
		contactImage = (ImageView) findViewById(R.id.contactImage);
		talkmessageCall = (Button) findViewById(R.id.talkmessage_call);
		talkmessageSend = (ImageButton) findViewById(R.id.talkmessage_send);
		talkmessageCall.setOnClickListener(this);
		talkmessageSend.setOnClickListener(this);
		contactImage.setOnClickListener(this);
		
		smsCallnum.setText(nhsmsSession.getAddress());
		if(contactUser != null){
			smsName.setText(contactUser.getName());
			contactImage.setImageBitmap(contactMgr.getContactHeadImgByPhotoId(contactUser.getPhotoId()));
		} else {
			smsCallnum.setTextSize(20);
			smsCallnum.setPadding(5, 16, 0, 0);
			smsName.setVisibility(View.GONE);
			contactImage.setImageBitmap(null);
		}
		
		messageAdapter = new TalkMessageAdapter(TalkMessageActivity.this, nhsmsList);
		talkmessage_list.setAdapter(messageAdapter);
	}
	
	private void initListView(){
		nhsmsList.addAll(nhsmsSession.getNhsms());
		
		if(nhsmsList.size() < nhsmsSession.getNumsize()){
			talkmessage_list.setHasHistoryData(true);
    	} else {
    		talkmessage_list.setHasHistoryData(false);
    	}
		
		messageAdapter.notifyDataSetChanged();
	}
	@Override
	public void onRefresh() {
		pageNumber ++;
		nhSmsMgr.getNhsmsListByTidLimit(nhsmsSession.getTid(), pageNumber);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.talkmessage_call){
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + nhsmsSession.getAddress()));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else if(v.getId() == R.id.contactImage){
			if(contactUser != null){
				Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse("content://com.android.contacts/contacts/" + contactUser.getContactId()));
				startActivity(intent);
			}
		} else if(v.getId() == R.id.talkmessage_send){
			if(talkmessageForbody.getText().toString().length() > 0){
				sendSms();
			}
		} else if(v.getId() == R.id.talkmessage_plus_file){
			if(appPanel.isShown()){
				appPanel.setVisibility(View.GONE);
			} else {
				appPanel.setVisibility(View.VISIBLE);
				hiddenImm(v);
			}
		} else if(v.getId() == R.id.checkbtn_cancel){
			mPopupWindow.dismiss();
			TalkMessageActivity.this.finish();
		} else if(v.getId() == R.id.checkbtn_ok){
			String signature = editText.getText().toString().trim();
			if(nhsmsSession.getCipher().equals(signature)){
				mPopupWindow.dismiss();
				mHandler.sendEmptyMessage(MSG_WHAT_UPDATE_READ);
				initListView();
			} else {
				editText.setText("");
				Toast.makeText(TalkMessageActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
			}
		}
		
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		Nhsms nhsms = messageAdapter.getItem(position - 1);
		if (nhsms == null)
			return false;

		final String content = nhsms.getBody();
		
		List<String> urllist = new ArrayList<String>();
		urllist.add(getResources().getString(R.string.msg_onlong_click_copy));
		
		final List<String> LinkList = LinkifyUtil.backLinks(content, LinkifyUtil.WEB_URLS | LinkifyUtil.EMAIL_ADDRESSES | LinkifyUtil.PHONE_NUMBERS);
		int linkSize = LinkList.size();
		String[] links = new String[linkSize + 1];
		links[0] = getResources().getString(R.string.msg_onlong_click_copy);
		for (int i = 0; i < linkSize; i++) {
			String link = LinkList.get(i);
			if(link.startsWith("http://") || link.startsWith("https://") || link.startsWith("rtsp://")){
				links[i+1] = link;
			} else if(link.startsWith("mailto:")){
				links[i+1] = link.replaceFirst("mailto", "邮件");
			} else if(link.startsWith("tel:")){
				links[i+1] = link.replaceFirst("tel", "电话");
			} else {
				links[i+1] = link;
			}
		}
		
		new LongClickDialog(TalkMessageActivity.this, links, getResources().getString(R.string.operation), new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position == ITEM_LONG_CLICK_COPY_INDEX){
					ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
					clipBoard.setText(content);
				} else {
					Uri uri = Uri.parse(LinkList.get(position-1));
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
					startActivity(intent);
				}
			}
		}).show();
		
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDataChanged(List<Nhsms> dataChangeList) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_DATA_CHANGE;
		message.obj = dataChangeList;
		mHandler.sendMessage(message);
	}
	
	private void finishActivityThing(){
		nhSmsMgr.setDataSetChangForSmsListener(null, -1);
		finish();
		System.gc();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK ){
			if(appPanel.isShown()){
        		appPanel.setVisibility(View.GONE);
        	} else {
        		finishActivityThing();
        	}
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	/**
     * 隐藏输入法
     *
     * @param view
     */
    private void hiddenImm(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    
	private void sendSms() {
		String smsBody = talkmessageForbody.getText().toString();
		talkmessageForbody.setText("");
        
    	Date date = new Date();
    	Nhsms nhsms = new Nhsms();
		nhsms.setAddress(nhsmsSession.getAddress());
		nhsms.setBody(smsBody);
		nhsms.setDate(date.getTime());
		nhsms.setDate_sent(date.getTime());
		nhsms.setError_code(0);
		nhsms.setLocked(0);
		nhsms.setProtocol(0);
		nhsms.setRead(1);
		nhsms.setReply_path_present(0);
		nhsms.setSeen(1);
		nhsms.setService_center("");
		nhsms.setStatus(Nhsms.STATUS_PENDING);
		nhsms.setSubject("");
		nhsms.setThread_id(-1);
		nhsms.setType(Nhsms.MESSAGE_TYPE_SENT);
		nhsms.setPerson(nhsmsSession.getPerson());
			
		List<Nhsms> nhsmsList = new ArrayList<Nhsms>();
		nhsmsList.add(nhsms);
        nhSmsMgr.sendSms(nhsmsList, null);
	}

}
